<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <h2>发放折扣</h2>

    <el-form-item label="优惠用户" prop="userId">
      <el-select-v2
        v-model="ruleForm.userId"
        placeholder="请选择优惠用户"
        :options="userList"
      />
    </el-form-item>

    <el-form-item label="优惠店铺" prop="shopId">
      <el-select-v2
        v-model="ruleForm.shopId"
        placeholder="请选择优惠商品"
        :options="shopList"
      />
    </el-form-item>

    <el-form-item label="优惠力度" prop="discount">
      <el-slider
        v-model="ruleForm.discount"
        :format-tooltip="formatTooltip"
        style="width: 400px"
      />
    </el-form-item>

    <el-form-item label="开始时间" required prop="startDate">
      <el-date-picker
        v-model="ruleForm.startDate"
        type="datetime"
        placeholder="Select date and time"
      />
    </el-form-item>

    <el-form-item label="结束时间" required prop="endDate">
      <el-date-picker
        v-model="ruleForm.endDate"
        type="datetime"
        placeholder="Select date and time"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"> Create </el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import axios from "axios";
import router from "@/router";

interface RuleForm {
  // discountId: string,
  // inputTime: Date;
  // state: number;
  userId: string;
  shopId: string;
  discount: number;
  startDate: Date;
  endDate: Date;
}

// interface RuleForm {
//   name: string;
//   region: string;
//   count: string;
//   date1: string;
//   date2: string;
//   delivery: boolean;
//   type: string[];
//   resource: string;
//   desc: string;
// }
const formatTooltip = (val: number) => {
  return val / 100;
};

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  userId: "",
  shopId: "",
  discount: 0,
  startDate: new Date(),
  endDate: new Date(),
});

const userList = ref([]); //用户列表
const shopList = ref([]); //商品列表

const checkEndDate = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请选择结束日期"));
  }
  setTimeout(() => {
    if (value < ruleForm.startDate) {
      callback(new Error("结束日期必须在开始日期之后"));
    } else {
      callback();
    }
  }, 1000);
};

const rules = reactive<FormRules<RuleForm>>({
  userId: [{ required: true, message: "请选择受折扣优惠的用户", trigger: "blur" }],
  shopId: [
    {
      required: true,
      message: "请选择受折扣优惠的商品",
      trigger: "blur",
    },
  ],
  startDate: [
    {
      type: "date",
      required: true,
      message: "请选择优惠券开始日期",
      trigger: "change",
    },
  ],
  endDate: [{ validator: checkEndDate, trigger: "blur" }],
});

const formattedDate = (optionDay: Date) => {
  const formatter = new Intl.DateTimeFormat("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false,
    timeZone: "Asia/Shanghai",
  });
  return formatter.format(optionDay).replace(/\//g, "-");
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");

      console.log(formattedDate(ruleForm.startDate));
      console.log(formattedDate(ruleForm.endDate));

      axios
        .post("/api/discount/insert", {
          userId: ruleForm.userId,
          shopId: ruleForm.shopId,
          discount: ruleForm.discount,
          startDate: formattedDate(new Date(ruleForm.startDate)),
          endDate: formattedDate(new Date(ruleForm.endDate)),
        })
        .then((res) => {
          console.log(res);
          if (res.data.success) {
            ElMessage({
              type: "success",
              message: "新建成功",
            });
            setTimeout(() => {
              router.push("/manager/discount");
            }, 100);
          } else {
            ElMessage({
              type: "error",
              message: res.data.message,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const getUserList = () => {
  axios
    .get("/api/user/options")
    .then((res) => {
      console.log(res);
      userList.value = res.data.message;
    })
    .catch((err) => {
      console.log(err);
    });
};

getUserList();

const getShopList = () => {
  axios
    .get("/api/shop/options")
    .then((res) => {
      console.log(res);
      shopList.value = res.data.message;
    })
    .catch((err) => {
      console.log(err);
    });
};

getShopList();

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
